var prop = {};
prop.init = function() {
    let img = mapImage();
    prop.featureids = [];
    $.get('/getallpropsofimg?img=' + img, function(e) {
        let fs = e.features;
        for (let index = 0; index < fs.length; index++) {
            const f = fs[index];
            prop.featureids.push(f.featureid);
            prop.createCard(f);
        }
        $.post('/getfeaturesofimg', { img: mapImage(), featureids: JSON.stringify(prop.featureids) }, function(result) {
            maps.drawFeatures(result.features);
        })
    });
    $('input[name=featurekeyword]').on('input', function(e) {
        let key = $(this).val();
        let url = '/getallpropsofimg?img=' + img;
        if (key != null) {
            url += '&kw=' + key;
        }
        prop.featureids = [];
        $.get(url, function(e) {
            $('.r-cards').find('.r-card').remove();
            let fs = e.features;
            for (let index = 0; index < fs.length; index++) {
                const f = fs[index];
                prop.featureids.push(f.featureid);
                prop.createCard(f);
            }
            $.post('/getfeaturesofimg', { img: mapImage(), featureids: JSON.stringify(prop.featureids) }, function(result) {
                maps.drawFeatures(result.features);
            })
        });
    });
}

prop.loadIcons = function(select) {
    $.get('/allicons', function(e) {
        $('.r-icons').html('');
        for (let index = 0; index < e.length; index++) {
            const icon = e[index];
            $('.r-icons').append("<div class='r-icon'></div>");
            $('.r-icons .r-icon:last').append("<img alt='" + icon + "' src='" + icon + "'/>");
        }
        $('.r-icons .r-icon').click(function(e) {
            $('.r-icons .r-icon').removeClass('r-icon-selected');
            $(this).addClass('r-icon-selected');
        });
        debugger;
        if (select)
            $('.r-icon').find('img[src=\'' + select + '\']').addClass('r-icon-selected');
    });
}
prop.addIcon = function() {
    layui.use('upload', function() {
        var upload = layui.upload;

        upload.render({
            elem: '#r-upload-icon' //绑定元素
                ,
            url: '/uploadicon/' //上传接口
                ,
            done: function(res) {
                if (res.status == 200) {
                    let icon = res.path;
                    $('.r-icons').append("<div class='r-icon'></div>");
                    $('.r-icons .r-icon:last').append("<img alt='" + icon + "' src='" + icon + "'/>");
                }
                $('.r-icons .r-icon:last').click(function(e) {
                    $('.r-icons .r-icon').removeClass('r-icon-selected');
                    $(this).addClass('r-icon-selected');
                });
            },
            error: function() {
                console.log("addIcon error");
            }
        });
    });
}
prop.UploadImg = function(id) {
    let domID = 'r-upload-img-btn';
    if (id != undefined)
        domID = id;
    layui.use('upload', function() {
        let img = mapImage();
        var upload = layui.upload;
        upload.render({
            elem: '#' + domID, //绑定元素,
            url: '/uploadfeatureimage/', //上传接口
            data: {
                featureid: $('.layui-form input[name=featureid]').val(),
                img: img
            },
            done: function(res) {
                if (res.status == 200) {
                    let path = res.path;
                    let tmpId = '#uploadPreView';
                    if (id != undefined) {
                        tmpId = '#' + domID + ' ' + tmpId;
                    }
                    layui.$(tmpId).removeClass('layui-hide').find('img').attr('src', path);
                }
            },
            error: function() {
                console.log("addIcon error");
            }
        });
    });
}
prop.removeProp = function(obj) {
    if ($(obj).hasClass('layui-btn-disabled')) return;
    if ($('.r-prop').length == 1) return;
    $(obj).parent().parent().parent().remove();
}
prop.addProp = function(obj) {
    if ($(obj).hasClass('layui-btn-disabled')) return;
    $(obj).parent().parent().parent().after($('.r-prop:last').clone());
}
prop.addNetaddr = function(obj) {
    if ($(obj).hasClass('layui-btn-disabled')) return;
    $(obj).parent().parent().parent().after($('.r-netaddr:last').clone());
}
prop.removeNetaddr = function(obj) {
    if ($(obj).hasClass('layui-btn-disabled')) return;
    if ($('.r-netaddr').length == 1) return;
    $(obj).parent().parent().parent().remove();
}
prop.addImage = function(obj) {
    if ($(obj).hasClass('layui-btn-disabled')) return;
    let clone = $('.r-images:last').clone();
    let id = 'r-upload-img-btn-' + window.guid();
    clone.find('.r-upload-img').attr('id', id);
    $(obj).parent().parent().parent().after(clone);
    prop.UploadImg(id);
}
prop.removeImage = function(obj) {
    if ($(obj).hasClass('layui-btn-disabled')) return;
    if ($('.r-images').length == 1) return;
    $(obj).parent().parent().parent().remove();
}

prop.save = function(obj) {
    if ($(obj).hasClass('layui-btn-disabled')) return;
    let featureid = $('.layui-form input[name=featureid]').val();
    let featurename = $('.layui-form input[name=featurename]').val();
    if (featureid == undefined || featureid.trim().length == 0) {
        layui.layer.msg("featureid 不能为空");
        return;
    }
    if (featurename == undefined || featurename.trim().length == 0) {
        layui.layer.msg("featurename 不能为空");
        return;
    }
    let icon = '';
    let tmp = $('.layui-form .r-icons .r-icon-selected');
    if (tmp.length > 0) icon = tmp.find('img').attr('src');
    let props = [];
    let netAddres = [];
    let images = [];
    let tmpProps = $('.r-prop');
    let tmpNetAddres = $('.r-netaddr');
    let tmpImages = $('.r-images');
    for (let index = 0; index < tmpProps.length; index++) {
        const tmpProp = tmpProps.eq(index);
        let attrName = tmpProp.find('input[name=propertyname]').val();
        let attrVal = tmpProp.find('textarea[name=propertydesc]').val();
        if (attrName == '' || attrVal == '') continue;
        props.push({
            propertyname: attrName,
            propertydesc: attrVal
        });
    }
    for (let index = 0; index < tmpNetAddres.length; index++) {
        const netAddr = tmpNetAddres.eq(index);
        let attrName = netAddr.find('input[name=netaddrname]').val();
        let attrVal = netAddr.find('input[name=netaddrdesc]').val();
        if (attrName == '' || attrVal == '') continue;
        netAddres.push({
            netaddrname: attrName,
            netaddrdesc: attrVal
        });
    }
    for (let index = 0; index < tmpImages.length; index++) {
        const image = tmpImages.eq(index);
        let attrName = image.find('img[id=imgpath]').attr('src');
        let attrVal = image.find('input[name=imgdesc]').val();
        if (attrVal == '') attrVal = '图片';
        if (attrName == '') continue;
        images.push({
            imgpath: attrName,
            imgdesc: attrVal
        });
    }
    let img = mapImage();
    let allData = {
        "featureid": featureid,
        "featurename": featurename == undefined || featurename.trim().length == 0 ? '未命名' : featurename,
        "img": img
    };
    if (icon != '') allData.icon = icon;
    if (props.length > 0) allData.props = props;
    if (netAddres.length > 0) allData.netAddres = netAddres;
    if (images.length > 0) allData.images = images;

    $.post('/saveproperties', { properties: JSON.stringify(allData) }, function(e) {
        layui.layer.closeAll('page');
    })
}

prop.createCard = function(featureGeoJson) {
    if ($('.r-cards').length === 0) return;
    let theFGS = featureGeoJson;
    if (prop.cardDomTemp != null) {
        create(theFGS);
    } else {
        $.get('/html/card.html', function(e) {
            prop.cardDomTemp = $(e);
            create(theFGS);
        });
    }

    function create(feat) {
        var cardTmp = prop.cardDomTemp.clone();
        cardTmp.feat = feat;
        let featureid = feat.featureid;
        let featurename = feat.featurename;
        let icon = feat.icon;
        let props = feat.props;
        let netAddres = feat.netAddres;
        let images = feat.images;
        //let img = feat.img;
        cardTmp.find('.featureid').html(featureid);
        cardTmp.find('.featurename').html(featurename);
        cardTmp.find('.icon img').attr('src', icon);

        let propDom = cardTmp.find('.r-card-propertyname').parent();
        for (let index = 0; props != undefined && index < props.length; index++) {
            const prop = props[index];
            if (prop.propertyname == '') continue;
            let tmpPropDom = propDom.clone();
            tmpPropDom.find('.r-card-propertyname').html(prop.propertyname);
            tmpPropDom.find('.r-card-propertydesc').html(prop.propertydesc);
            propDom.parent().append(tmpPropDom);
        }
        propDom.remove();

        let netAddresDom = cardTmp.find('.r-card-netaddresses');
        netAddresDom.html('');
        for (let index = 0; netAddres != undefined && index < netAddres.length; index++) {
            const netAddre = netAddres[index];
            let tmpAddDom = $('<a target="black" href="' + netAddre.netaddrdesc + '">' + netAddre.netaddrname + '</a>')
            netAddresDom.append(tmpAddDom);
        }

        let imagesDom = cardTmp.find('.r-card-imgpath').parent();
        for (let index = 0; images != undefined && index < images.length; index++) {
            const image = images[index];
            if (image.imgpath == '') continue;
            let tmpImageDom = imagesDom.clone();
            tmpImageDom.find('.r-card-imgpath img').attr('src', image.imgpath);
            tmpImageDom.find('.r-card-imgdesc').html(image.imgdesc);
            imagesDom.parent().append(tmpImageDom);
        }
        imagesDom.remove();
        cardTmp.find('button').attr('featureid', featureid);
        $('.r-cards').append(cardTmp);
    }
}
prop.viewImage = function(obj) {
    layui.layer.open({
        title: '图片',
        area: ['800px', '650px'],
        type: 1,
        maxmin: true,
        content: $(obj).clone().css({
            'width': 'auto',
            'height': 'auto',
            'max-width': '100%',
            'max-height': '100%'
        }).attr("onclick", null).off("click")[0].outerHTML
    });
}
prop.flyto = function(btn) {
    let featid = $(btn).attr('featureid');
    maps.panByFeatureid(featid);
}
prop.viewOrEditFeat = function(btn) {
    let featid = $(btn).attr('featureid');
    let theType = $(btn).html();
    let img = mapImage();
    $.get('/getallpropsofimg?img=' + img + '&featureid=' + featid, function(e) {
        let fs = e.features;
        if (fs.length === 0) return;
        let f = fs[0];
        let type = theType;
        if (prop.propertiesDomTemp != null) {
            create(f, type);
        } else {
            $.get('/html/addproperties.html', function(e) {
                prop.propertiesDomTemp = $(e);
                create(f, type);
            });
        }
    });

    function create(feat, type) {
        var form = prop.propertiesDomTemp.clone();

        let featureid = feat.featureid;
        let featurename = feat.featurename;
        let icon = feat.icon;
        let props = feat.props;
        let netAddres = feat.netAddres;
        let images = feat.images;
        //let img = feat.img;
        form.find('[name=featureid]').attr('value', featureid);
        form.find('[name=featurename]').attr('value', featurename);

        let select = undefined;
        if (icon != '')
            select = icon;
        if ((props == undefined || 0 == props.length) && type == '查看') {
            form.find('.r-prop').remove();
        }
        for (let index = 0; props != undefined && index < props.length; index++) {
            const prop = props[index];
            if (prop.propertyname == '') continue;
            let tmpPropDom = index === 0 ? form.find('.r-prop') : form.find('.r-prop').clone();
            tmpPropDom.find('[name=propertyname]').attr('value', prop.propertyname);
            tmpPropDom.find('[name=propertydesc]').html(prop.propertydesc);
            if (index > 0) form.find('.r-prop:last').parent().after(tmpPropDom);
        }

        if ((netAddres == undefined || 0 == netAddres.length) && type == '查看') {
            form.find('.r-netaddr').remove();
        }
        for (let index = 0; netAddres != undefined && index < netAddres.length; index++) {
            const prop = netAddres[index];
            if (prop.netaddrdesc == '') continue;
            let tmpPropDom = index === 0 ? form.find('.r-netaddr') : form.find('.r-netaddr').clone();
            tmpPropDom.find('[name=netaddrname]').attr('value', prop.netaddrname);
            tmpPropDom.find('[name=netaddrdesc]').attr('value', prop.netaddrdesc);
            if (index > 0) form.find('.r-netaddr:last').parent().after(tmpPropDom);
        }

        if ((images == undefined || 0 == images.length) && type == '查看') {
            form.find('.r-images').remove();
        }
        for (let index = 0; images != undefined && index < images.length; index++) {
            const prop = images[index];
            if (prop.imgdesc == '') continue;
            let tmpPropDom = index === 0 ? form.find('.r-images') : form.find('.r-images').clone();
            tmpPropDom.find('[name=imgdesc]').attr('value', prop.imgdesc);
            tmpPropDom.find('[id=imgpath]').attr('src', prop.imgpath);
            if (index > 0) form.find('.r-images:last').parent().after(tmpPropDom);
        }
        if (type != '编辑') {
            form.find('button').addClass('layui-btn-disabled');
        }
        let tmpId = '#uploadPreView';
        form.find(tmpId).removeClass('layui-hide');
        let digTitle = '编辑';
        if (type == '查看') {
            digTitle = "查看";
        }
        layui.layer.open({
            title: digTitle,
            area: ['800px', '650px'],
            type: 1,
            shade: 0,
            resize: false,
            maxmin: false,
            content: form[0].outerHTML
        });
        prop.loadIcons(select);
        prop.addIcon();
        prop.UploadImg();
    }
}